package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JwtUtils;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.media.dtos.WmUserLoginDto;
import com.heima.wemedia.entity.WmUser;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-10-19
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> login(WmUserLoginDto dto) {
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName,dto.getName());
//        根据name查询用户
        WmUser wmUser = getOne(queryWrapper);
//        如果没有用户，抛异常
        if(wmUser == null){
            log.error("没有对应的用户，name={}"+dto.getName());
            throw new LeadException(AppHttpCodeEnum.WM_USER_DATA_NOT_EXIST);
        }
//        验证密码
        boolean b = passwordEncoder.matches(dto.getPassword(), wmUser.getPassword());
        if(!b){
            log.error("密码不正确！");
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        生成token
        String token = JwtUtils.generateTokenExpireInMinutes(wmUser.getId(), 120);
//        构造返回对象
        wmUser.setPassword(null);
        Map<String, Object> map = new HashMap<>();
        map.put("user",wmUser);
        map.put("token",token);
        return map;
    }

    @Override
    public Integer saveUser(WmUserDto dto) {
        Integer apUserId = dto.getApUserId();
        LambdaQueryWrapper<WmUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WmUser::getApUserId, apUserId);
        WmUser wmUser = getOne(lqw);
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUserId);
            wmUser.setPhone(dto.getPhone());
            wmUser.setPassword(dto.getPassword());
            wmUser.setStatus(dto.getStatus());
        }
        wmUser.setName(dto.getName());
//        新增或修改数据
        boolean b = saveOrUpdate(wmUser);
        return wmUser.getId();
    }
}
